package cn.touna.jss.modules.third.jiguang;

import cn.touna.risk.api.contraints.facet.First;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.JiguangProperties;
import cn.touna.jss.common.util.Base64;
import cn.touna.jss.common.util.JssConstant;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.jiguang.entity.JiguangRequestEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.http.HttpsUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * \* User: MeiZhongHao
 * \* Date: 2018-05-07
 * \* Time: 11:47
 * \* Description:
 * \
 */
@Service
public class JiguangService {

    private final static Logger logger = LogManager.getLogger(JiguangService.class);

    // 三方接口返回状态码key
    private final static String STATUS_CODE = "code";
    // 三方接口返回值key
    private final static String DATA = "data";
    // 三方接口返回状态码说明key
    private final static String MSG = "message";
    // 三方接口返回成功状态码
    private final static int JIGUANG_SUCCESS_CODE = 2000;
    @Autowired
    private JiguangProperties jiguangProperties;

    @ApiMapping(value = "jiguang.basetag",desc = "极光.基础标签查询")
    public Response queryFinance(JiguangRequestEntity jiguangRequestEntity){
        //校验
        Response validResponse = ValidUtil.valid(jiguangRequestEntity, First.class);
        if (validResponse != null)
            return validResponse;
        String url = jiguangProperties.getBaseurl()+jiguangProperties.getTagbaseurl();
        Map<String, String> headParams = getHeadParams();
        Map<String,String> requestBody = paramsAssemble(jiguangRequestEntity);
        try {
            String res = HttpsUtil.getInstance().get(url,requestBody,headParams);
            JSONObject result = JSONObject.parseObject(res);
            // 若请求返回2000则请求成功
            if (result.getInteger(STATUS_CODE) != null &&
                    result.getInteger(STATUS_CODE).equals(JIGUANG_SUCCESS_CODE)) {
                return ResponseFactory.success(result);
            }
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,result.getString(MSG));
        }catch (Exception e){
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }

    @ApiMapping(value = "jiguang.address",desc = "极光.地址标签查询")
    public Response queryAddress(JiguangRequestEntity jiguangRequestEntity){
        //校验
        Response validResponse = ValidUtil.valid(jiguangRequestEntity, First.class);
        if (validResponse != null)
            return validResponse;
        String url = jiguangProperties.getBaseurl()+jiguangProperties.getAddressurl();
        Map<String, String> headParams = getHeadParams();
        Map<String,String> requestBody = paramsAssemble(jiguangRequestEntity);
        try {
            String res = HttpsUtil.getInstance().get(url,requestBody,headParams);
            JSONObject result = JSONObject.parseObject(res);
            if (result.getInteger(STATUS_CODE) != null &&
                    result.getInteger(STATUS_CODE).equals(JIGUANG_SUCCESS_CODE)) {
                return ResponseFactory.success(result);
            }
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,result.getString(MSG));
        }catch (Exception e){
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }

    @ApiMapping(value = "jiguang.blacklist",desc = "极光.黑名单查询")
    public Response queryBlacklist(JiguangRequestEntity jiguangRequestEntity){
        //校验
        Response validResponse = ValidUtil.valid(jiguangRequestEntity, First.class);
        if (validResponse != null)
            return validResponse;
        String url = jiguangProperties.getBaseurl()+jiguangProperties.getBlacklisturl();
        Map<String, String> headParams = getHeadParams();
        Map<String,String> requestBody = paramsAssemble(jiguangRequestEntity);
        try {
            String res = HttpsUtil.getInstance().get(url,requestBody,headParams);
            JSONObject result = JSONObject.parseObject(res);
            if (result.getInteger(STATUS_CODE) != null &&
                    result.getInteger(STATUS_CODE).equals(JIGUANG_SUCCESS_CODE)) {
                return ResponseFactory.success(result);
            }
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,result.getString(MSG));
        }catch (Exception e){
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }

    private Map<String,String> paramsAssemble(JiguangRequestEntity jiguangRequestEntity){
        Map<String,String> map = new HashMap<>();
        if (!StringUtils.isEmpty(jiguangRequestEntity.getImei())){
            map.put("imei",jiguangRequestEntity.getImei());
        }
        if (!StringUtils.isEmpty(jiguangRequestEntity.getMobile())){
            map.put("phone",jiguangRequestEntity.getMobile());
        }
        if (!StringUtils.isEmpty(jiguangRequestEntity.getMobileMd5())){
            map.put("phone_md5",jiguangRequestEntity.getMobileMd5());
        }
        if (!StringUtils.isEmpty(jiguangRequestEntity.getMac())){
            map.put("mac",jiguangRequestEntity.getMac());
        }
        if (!StringUtils.isEmpty(jiguangRequestEntity.getImsi())){
            map.put("imsi",jiguangRequestEntity.getImsi());
        }
        if (!StringUtils.isEmpty(jiguangRequestEntity.getTag())){
            map.put("tag",jiguangRequestEntity.getTag());
        }
        if (!StringUtils.isEmpty(jiguangRequestEntity.getName())){
            map.put("name",jiguangRequestEntity.getName());
        }
        if (!StringUtils.isEmpty(jiguangRequestEntity.getIdCard())){
            map.put("id_number",jiguangRequestEntity.getIdCard());
        }
        return map;
    }

    private Map<String, String> getHeadParams() {
        Map<String, String> headParams = new HashMap<>();
        String devkey = jiguangProperties.getDevkey();
        String devsecret = jiguangProperties.getDevsecret();
        StringBuilder signBuilder = new StringBuilder();
        headParams.put(HttpHeaders.AUTHORIZATION, "Basic "+Base64.encode((devkey+":"+devsecret).getBytes()));
        headParams.put("Content-Type", JssConstant.JSON_MEDIA_TYPE);
        return headParams;
    }

}